<?php
namespace common\components;

use Yii;
use yii\base\Component;
use OSS\OssClient;
use OSS\Core\OssException;

/**
 * oss sdk aliyun
 */
class OssSdk extends Component
{

    /** 您从OSS获得的AccessKeyId */
    public $access_key_id;

    /** 您从OSS获得的AccessKeySecret */
    public $access_key_secret;

    /** 您选定的OSS数据中心访问域名，例如http://oss-cn-hangzhou.aliyuncs.com */
    public $endpoint;

    /** 您使用的Bucket名字，注意命名规范 */
    public $bucket;

    private static $_ossClient;

    public function init()
    {
        parent::init();
        if (!self::$_ossClient instanceof OssClient) {
            try {
                self::$_ossClient = Yii::createObject('OSS\OssClient', [
                    $this->access_key_id,
                    $this->access_key_secret,
                    $this->endpoint
                ]);
            } catch (OssException $e) {
                throw new OssException($e->getMessage());
            }
        }

    }

    /**
     * 上传文件
     */
    public function putObject($object, $content)
    {
        return self::$_ossClient->putObject($this->bucket, $object, $content);
    }

    /**
     * 获取当前BUCKET的所有文件
     */
    public static function listAllObjects($options = null)
    {
        return self::$_ossClient->listObjects($this->bucket, $options)->getObjectList();
    }


}
